package com.adingxiong.cft.controller;


import com.adingxiong.cft.annotate.Mylog;
import com.adingxiong.cft.config.ApplicationProperties;
import com.adingxiong.cft.controller.oauth.MayunOauth;
import com.adingxiong.cft.entity.Role;
import com.adingxiong.cft.entity.TUser;
import com.adingxiong.cft.entity.dto.*;
import com.adingxiong.cft.entity.oauth.Oauth;
import com.adingxiong.cft.errors.Assert;
import com.adingxiong.cft.result.Result;
import com.adingxiong.cft.service.IRoleService;
import com.adingxiong.cft.service.ITUserService;
import com.adingxiong.cft.service.IUserRoleService;
import com.adingxiong.cft.service.UserCacheService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xiongc
 * @since 2020-09-22
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@Slf4j
public class TUserController {

    @Autowired
    private ITUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private UserCacheService cacheService;

    @Autowired
    private ApplicationProperties applicationProperties;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginParam loginParam ){
        String token = userService.login(loginParam.getUsername(),loginParam.getPassword());
        if(token == null){
            return Result.validateFailed("用户名或者密码错误");
        }
        Map<String,Object> res = new HashMap<>();
        res.put("token" ,token);
        res.put("tokenHead",applicationProperties.getTokenHead());
        return Result.success(res);
    }


    @ApiOperation(value = "跳转码云第三方登录")
    @GetMapping("/login/oauth")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        log.info("跳转第三方登陆认证");
        try {
            response.sendRedirect(MayunOauth.mayunURI);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    @GetMapping("/login/callback")
    public Result login(@RequestParam(value = "code") String code ) {
        log.info("认证成功返回的code为:{}" ,code);

        String token  = userService.getToken(code);
        JSONObject parse = (JSONObject) JSONObject.parse(token);
        Oauth oauth = JSONObject.toJavaObject(parse,Oauth.class);

        Map<String,Object> res  = userService.getUserInfo(oauth.getAccessToken());

        return Result.success(res);
    }


    @Mylog(value = "获取当前用户信息")
    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/info")
    public Result<Map<String,Object>> getUserInfo(Principal principal){
        if(principal == null){
            return Result.unauthorized(null);
        }
        String username = principal.getName();
        TUser user = null;
        user = cacheService.getUser(username);
        if(user == null){
            user = userService.getUserByUsername(username);
            cacheService.setUserInfo(user);
        }
        List<Role> list = roleService.getUserRole(user.getId());
        Map<String,Object> res = new HashMap<>();
        res.put("userInfo",user);
        res.put("role",list);
        return Result.success(res);
    }


    @Mylog(value = "刷新token")
    @ApiOperation(value = "刷新token")
    @GetMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request){
        String token = request.getHeader(applicationProperties.getTokenHeader());
        String newToken = userService.refreshToken(token);
        if(newToken == null) {
            Assert.fail("token 已经过期");
        }
        Map<String,Object> res = new HashMap<>();
        res.put("tokenHead" ,applicationProperties.getTokenHead());
        res.put("token" ,newToken);
        return Result.success(res);

    }

    @GetMapping("/logout")
    @ApiOperation(value = "退出登录")
    public Result logOut(HttpServletRequest request) {
        userService.logOut(request);
        return Result.success(null);
    }


    @PostMapping("/register")
    @ApiOperation(value = "注册账号")
    public Result<TUser> userRegister(@Validated @RequestBody UserRegister register){
        TUser tuser = userService.register(register);
        if(tuser == null){
            return Result.failed();
        }
        return Result.success(tuser);
    }


    @Mylog(value = "查询用户列表")
    @GetMapping("/list")
    @ApiOperation(value = "分页查询")
    public Result<Page<TUser>> findByKeyWords(
            @ApiParam(value = "keywords",name = "关键字") @RequestParam(value = "keywords",required = false) String keywords,
            @ApiParam(value = "pageSize",name = "当前页码") @RequestParam(value = "pageSize",required = false,defaultValue = "5") Integer pageSize,
            @ApiParam(value = "pageNum",name = "每页条数") @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum
    ){
        Page<TUser> userPage = userService.list(keywords,pageSize,pageNum);
        return Result.success(userPage);
    }

    @GetMapping("/user/{id}")
    @ApiOperation(value = "根据id查询用户信息")
    public Result<Map<String,Object>> getOne(@PathVariable Integer id){
        TUser user = userService.getById(id);
        List<Role> list = roleService.getUserRole(id);
        Map<String,Object> res = new HashMap<>();
        res.put("user",user);
        res.put("role",list);
        return Result.success(res);
    }


    @PostMapping("/update/{id}")
    @ApiOperation(value = "更新用户信息")
    public Result  updateById(@PathVariable Integer id ,@RequestBody TUser user){
        boolean update = userService.update(id,user);
        return update ? Result.success(update) : Result.failed();
    }

    @PostMapping("/updatepwd")
    @ApiOperation(value = "修改用户密码")
    public Result updatePassword(@RequestBody UpdatePasswordParam param){
        int res = userService.updatePassword(param);
        return Result.success(res);
    }

    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据id删除指定用户")
    public Result delUserById(@PathVariable Integer id){
        boolean del = userService.removeById(id);
        return del ? Result.success(del) : Result.failed("删除失败");
    }

    @PostMapping("/update/status/{id}")
    @ApiOperation(value = "修改用户的状态")
    public Result updateStatus(@PathVariable Integer id ){
        TUser user = userService.getById(id);
        if(user.getStatus().equals(1)){
            user.setStatus(0);
        }else{
            user.setStatus(1);
        }
        boolean update = userService.updateById(user);
        return update ? Result.success(update) : Result.failed("修改状态失败");
    }


    @PostMapping("/addrole")
    @ApiOperation(value = "添加用户角色")
    public Result setUserRole(@Validated @RequestBody UserRoleBo bo){
        boolean add = userRoleService.save(bo);
        return Result.success(add);
    }

    @GetMapping("/online")
    @ApiOperation(value = "获取当前在线用户")
    public Result<List<OnlineUser>> getOnlineUser(){
        List<OnlineUser> users = userService.getOnline();
        return Result.success(users);
    }

}

